<template>
    <div>
        <cus-modal ref="modal" title="智能匹配" @on-visible-change="onVisibleChange" :width="1000"  @onOk="onOk"
            cancelBtnName="关闭">
            <Spin fix v-if="loading"></Spin>
            <div class="contentBox">
                <div style="width: 920px">
                    <Form ref="formValidate" style="justify-content: start" :model="ingredientsForm">
                        <FormItem label="食材名称:" prop="materialName" style="margin-right: 20px" :label-width="80">
                            <Input v-model="ingredientsForm.materialName" maxlength="20" clearable placeholder="请输入食材名称"
                                style="width: 100px">
                            </Input>
                        </FormItem>
                        <FormItem label="状态:" prop="matchState" :label-width="50" style="margin-right: 20px">
                            <Select v-model="ingredientsForm.matchState" style="width: 100px" placeholder="请选择状态"
                                clearable>
                                <Option :value="-1">全部</Option>
                                <Option :value="1">已匹配</Option>
                                <Option :value="0">未匹配</Option>
                            </Select>
                        </FormItem>
                        <Button class="ml_24" matchState="primary" type="primary" @click="
                            pages.page = 1;
                        autoproductMatchReviewPageApi();
                        ">查询</Button>
                    </Form>
                </div>
                <div style=" width: 920px">
                    <Table border :loading="loading" :columns="columns" :rowClassName="rowClassName" :data="data" height="500" :span-method="handleSpan">
                        <template slot-scope="{ row }" slot="operation">
                            <div class="flex" v-if="row.noBind">
                                <cus-button type="text" size="small" :style="{ color: '#1E6FFF', padding: '0 8px' }"
                                    @onClick="onPriority(row)">
                                    {{ row.priority ? '优先采购' : '设置优先' }}
                                </cus-button>
                                <cus-button type="text" size="small" @onClick="onCancelBind(row)" :style="{
                                    color: '#FF4746',
                                    padding: '0 8px',
                                }">
                                    删除
                                </cus-button>

                            </div>
                            <div class="flex" v-else>
                           
                                <cus-button type="text" size="small"  :style="{
                                    color: '#FF4746',
                                    padding: '0 8px',
                                }">
                                    未匹配
                                </cus-button>

                            </div>
                        </template>
                    </Table>
                    <div style="width: 100%; text-align: right">
                        <cus-page :data="pages" class="mt_10" @pageChange="autoFoodProductMatchingApi()"
                            :showSizer="false" :showElevator="false"></cus-page>
                    </div>
                </div>
            </div>
        </cus-modal>
    </div>
</template>

<script>
import {
    saveFoodProductMatching,
    deleteFoodProductMatchingPriority,
    updateFoodProductMatchingPriority,
    autoFoodProductMatching,
    autoproductMatchReviewPage,
    settingPriority,
    deleteReviewDetail,
    saveFoodProductMatch
} from "@/api/organ/dishesModule";


const form = {
    matchState: -1, // 匹配类型
    materialName: "", // 商品名称
};

export default {
    data() {
        return {
            ingredientsForm: form,
            ruleValidate: {},
            loading: false,
            loading2: false,
            materialmatchStateList: [],
            areaList: this.$store.state.selectList.areaList, //区域
            specificationList: [],
            foodRulematchStateList: [],
            columns: [
                {
                    title: "序号",
                    width: 70,
                    key: "index",
                    align: "center",
                },
                {
                    title: "原料名称",
                    key: "materialName",
                    align: "center",
                },
                {
                    title: "商品名称",
                    key: "productName",
                    align: "center",
                },
                {
                    title: "供应商",
                    key: "supplyName",
                    align: "center",
                },
                {
                    title: "品牌",
                    key: "brand",
                    align: "center",
                },
                {
                    title: "计量单位",
                    key: "packagingUnit",
                    align: "center",
                },
                {
                    title: "价格",
                    key: "packagingPrice",
                    align: "center",
                },
                {
                    title: "操作",
                    slot: "operation",
                    width: 200,
                    align: "center",
                },
            ],

            data: [],
            pages: {
                page: 1,
                pageSize: 10,
                pageTotal: 0,
            },
            selectItem: null,
            selectRightItem: null,
            step: 1,
            single: false,
        };
    },
    props: {
        kitchenArea: {
            type: [Number, String],
            default: ''
        },
    },
    mounted() {
        this.ingredientsForm = this.$cu.deepClone(form);
    },
    methods: {
        onVisibleChange(v) {
            if (!v) {
                this.ingredientsForm = this.$cu.deepClone(form);
                this.selectItem = null;
                this.selectRightItem = null;
                this.step = 1;
                this.single = false;
            }
        },
            // 给特定的行添加类
    rowClassName(row, index) {
      console.log(row,'控制yanse');
      
      // 根据条件给特定行添加颜色
      if (row.priority) {
        return 'activeRow';
      }
      return '';
    },
        show() {
            this.$refs["modal"].show = true;
            this.autoFoodProductMatchingApi();
        },
        onOk() {
            this.saveFoodProductMatchApi()
        },

        handleSpan({ row, column, rowIndex, columnIndex }) {
            // console.log(row,'匹配',rowIndex,row.length);
            // console.log('界面数据');
            if ( columnIndex < 2) {
                console.log(row.clospan,'长度' );
                
                return [row.clospan,row.clospan ? 1  : 0];
                }
        },
        // 设置优先
        onPriority(row) {
            if(row.priority == 0)    this.settingPriorityApi(row.id)
        },
      // 取消匹配
  onCancelBind(item) {
    this.deleteReviewDetailApi(item.id)
  },
        // 自动绑定食材
        autoFoodProductMatchingApi() {
            this.loading = true;
            return new Promise((resolve) => {
                autoFoodProductMatching({
                    kitchenArea: this.kitchenArea,
                }).then((res) => {
                    this.loading = false;
                    if (res.code === 1) {
                        this.autoproductMatchReviewPageApi()
                        resolve();
                    }
                });
            });
        },
        // 商品列表
        autoproductMatchReviewPageApi() {
            this.selectRightItem = null;
            this.loading2 = true;
            this.data = []
            return new Promise((resolve) => {
                autoproductMatchReviewPage({
                    materialName: this.ingredientsForm.materialName,
                    matchState: this.ingredientsForm.matchState,
                    current: this.pages.page,
                    size: this.pages.pageSize,
                }).then((res) => {
                    this.loading2 = false;
                    if (res.code === 1) {
                        // 
              
                        
                        res.data.list.forEach((item,ind) => {
                            if(item.productMatchReviewDetailEntityList.length) {
                                console.log('进入了');
                                item.productMatchReviewDetailEntityList.forEach((it,idx) => {
                                let newIt = it
                                newIt.noBind = true
                                newIt.materialName = item.materialName
                                newIt.clospan = idx ? 0 : item.productMatchReviewDetailEntityList.length
                                newIt.index = ind + 1
                                newIt.length =  item.productMatchReviewDetailEntityList.length
                                this.data.push(JSON.parse(JSON.stringify(newIt)))
                                }) 
                            }else {
                                item.noBind = false
                                item.index = ind + 1
                                item.clospan = 1
                                this.data.push(JSON.parse(JSON.stringify(item)))
                            }
                        })
                        console.log(this.data,'最终数据');
                        
                        this.pages.pageTotal = res.data.total;
                        resolve();
                    }
                });
            });
        },
        // 设置为优先
        settingPriorityApi(id) {
            this.loading = true;
            return new Promise(resolve => {
                settingPriority({
                    id: id
                }).then(res => {
                    this.loading = false;
                    if(res.code == 1) {
                        this.autoproductMatchReviewPageApi()
                    }
                })
            })
        },
                // 删除匹配
                deleteReviewDetailApi(id) {
            this.loading = true;
            return new Promise(resolve => {
                deleteReviewDetail({
                    id: id
                }).then(res => {
                    this.loading = false;
                    if(res.code == 1) {
                        this.autoproductMatchReviewPageApi()
                    }
                })
            })
        },
        
        // 保存
        saveFoodProductMatchApi() {
            this.loading = true;
            return new Promise(resolve => {
                saveFoodProductMatch({
                    reviewIds: []
                }).then(res => {
                    this.loading = false;
                    if(res.code == 1) {
                        console.log(122333);
                        this.$Message.success("智能匹配成功");
                        this.$emit('onOk')
                        this.$refs["modal"].show = false;
                     
                    }
                })
            })
        },

    },
};
</script>

<style scoped>
/deep/.ivu-select-multiple .ivu-select-selection .ivu-select-placeholder {
    /* height: 40px !important; */
    height: auto !important;
    line-height: 32px !important;
}

/deep/.ivu-select-selection {
    height: auto !important;
    min-height: 32px !important;
    border-radius: 2px !important;
}

/deep/.ivu-table-cell {
    padding-left: 0 !important;
    padding-right: 0 !important;
    padding-top: 0 !important;
    padding-bottom: 0 !important;
}

/deep/.ivu-table td {
    position: relative !important;
}
/deep/  .activeRow > .ivu-table-column-center {
    background-color: #80bffe !important;
}
/deep/ .activeRow {
background-color: #80bffe !important;
}
</style>

<style scoped lang="less">



.contentBox {
    display: flex;
    justify-content: space-between;
    flex-direction: column;
}
</style>